import React, { useState, useEffect } from 'react';
import axios from 'axios';

const CurrentQualificationsForm = ({ applicationId }) => {
    const [currentQualifications, setCurrentQualifications] = useState([]);
    const [newQualification, setNewQualification] = useState({
        qualificationName: '',
        qualificationLevel: '',
        profession: '',
        issuingAuthority: '',
        certificateNo: '',
        issuingUnit: '',
        remarks: ''
    });
    const [editingId, setEditingId] = useState(null);

    useEffect(() => {
        const fetchCurrentQualifications = async () => {
            try {
                const response = await axios.get(`/api/applications/${applicationId}/current-qualifications`);
                setCurrentQualifications(response.data);
            } catch (error) {
                console.error('Error fetching current qualifications:', error);
            }
        };

        if (applicationId) {
            fetchCurrentQualifications();
        }
    }, [applicationId]);

    const handleChange = (e) => {
        const { name, value } = e.target;
        setNewQualification(prevInfo => ({
            ...prevInfo,
            [name]: value
        }));
    };

    const handleAddOrUpdate = async (e) => {
        e.preventDefault();
        try {
            if (editingId) {
                await axios.put(`/api/applications/${applicationId}/current-qualifications/${editingId}`, newQualification);
                alert('现专业技术资格(职业资格)更新成功！');
            } else {
                await axios.post(`/api/applications/${applicationId}/current-qualifications`, newQualification);
                alert('现专业技术资格(职业资格)添加成功！');
            }
            setNewQualification({
                qualificationName: '',
                qualificationLevel: '',
                profession: '',
                issuingAuthority: '',
                certificateNo: '',
                issuingUnit: '',
                remarks: ''
            });
            setEditingId(null);
            const response = await axios.get(`/api/applications/${applicationId}/current-qualifications`);
            setCurrentQualifications(response.data);
        } catch (error) {
            console.error('Error saving current qualification:', error);
            alert('保存失败，请重试。');
        }
    };

    const handleEdit = (info) => {
        setNewQualification(info);
        setEditingId(info.id);
    };

    const handleDelete = async (id) => {
        try {
            await axios.delete(`/api/applications/${applicationId}/current-qualifications/${id}`);
            alert('现专业技术资格(职业资格)删除成功！');
            setCurrentQualifications(currentQualifications.filter(info => info.id !== id));
        } catch (error) {
            console.error('Error deleting current qualification:', error);
            alert('删除失败，请重试。');
        }
    };

    return (
        <div className="form-container">
            <h3>现专业技术资格(职业资格)</h3>
            <form onSubmit={handleAddOrUpdate}>
                <div className="form-group">
                    <label>资格名称:</label>
                    <input type="text" name="qualificationName" value={newQualification.qualificationName} onChange={handleChange} required />
                </div>
                <div className="form-group">
                    <label>资格等级:</label>
                    <input type="text" name="qualificationLevel" value={newQualification.qualificationLevel} onChange={handleChange} />
                </div>
                <div className="form-group">
                    <label>专业:</label>
                    <input type="text" name="profession" value={newQualification.profession} onChange={handleChange} />
                </div>
                <div className="form-group">
                    <label>发证机关:</label>
                    <input type="text" name="issuingAuthority" value={newQualification.issuingAuthority} onChange={handleChange} />
                </div>
                <div className="form-group">
                    <label>证书编号:</label>
                    <input type="text" name="certificateNo" value={newQualification.certificateNo} onChange={handleChange} />
                </div>
                <div className="form-group">
                    <label>发证单位:</label>
                    <input type="text" name="issuingUnit" value={newQualification.issuingUnit} onChange={handleChange} />
                </div>
                <div className="form-group">
                    <label>备注:</label>
                    <textarea name="remarks" value={newQualification.remarks} onChange={handleChange}></textarea>
                </div>
                <button type="submit">{editingId ? '更新' : '添加'}</button>
            </form>

            <h4>已添加现专业技术资格(职业资格)</h4>
            <table>
                <thead>
                    <tr>
                        <th>资格名称</th>
                        <th>资格等级</th>
                        <th>专业</th>
                        <th>发证机关</th>
                        <th>证书编号</th>
                        <th>发证单位</th>
                        <th>备注</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    {currentQualifications.map(info => (
                        <tr key={info.id}>
                            <td>{info.qualificationName}</td>
                            <td>{info.qualificationLevel}</td>
                            <td>{info.profession}</td>
                            <td>{info.issuingAuthority}</td>
                            <td>{info.certificateNo}</td>
                            <td>{info.issuingUnit}</td>
                            <td>{info.remarks}</td>
                            <td>
                                <button onClick={() => handleEdit(info)}>编辑</button>
                                <button onClick={() => handleDelete(info.id)}>删除</button>
                            </td>
                        </tr>
                    ))}
                </tbody>
            </table>
        </div>
    );
};

export default CurrentQualificationsForm;

